package stat;

import com.xeiam.xchart.Chart;
import tsd.TSD;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Author: Oleg Yasnev (oyasnev@gmail.com)
 * Date: 24.05.14
 */
public class TSDDistChart extends TSDStatChart {

    public String seriesName2;
    protected ArrayList<Double> xData2, yData2;

    public TSDDistChart(int locX, int locY) {
        super(locX, locY);
        xData2 = new ArrayList<Double>();
        yData2 = new ArrayList<Double>();
        chartHeader = "TSD distance from repeat distribution";
        chartTitle  = "TSD distance from repeat distribution";
        xTitle      = "Distance";
        yTitle      = "Count";
        seriesName  = "Start of repeat";
        seriesName2 = "End of repeat";
    }

    @Override
    protected void updateData(List<TSD> tsdList) {
        Map<Integer, Integer> mapLeft = new TreeMap<Integer, Integer>();
        Map<Integer, Integer> mapRight = new TreeMap<Integer, Integer>();
        for (TSD tsd : tsdList) {
            if (tsd.hasTSD) {
                int distLeft, distRight;
                if (!tsd.repeat.complement) {
                    // forward strand
                    distLeft  = tsd.repeat.posQBegin - tsd.startPos - tsd.alignedStart.length();
                    distRight = tsd.endPos - tsd.repeat.posQEnd - 1;
                } else {
                    // complement strand
                    distRight = tsd.repeat.posQBegin - tsd.startPos - tsd.alignedStart.length();
                    distLeft = tsd.endPos - tsd.repeat.posQEnd - 1;
                }

                int count = mapLeft.containsKey(distLeft) ? mapLeft.get(distLeft) : 0;
                mapLeft.put(distLeft, count + 1);
                count = mapRight.containsKey(distRight) ? mapRight.get(distRight) : 0;
                mapRight.put(distRight, count + 1);
            }
        }

        xData.clear();
        yData.clear();
        for (Integer x : mapLeft.keySet()) {
            xData.add(x * 1.0);
            yData.add(mapLeft.get(x) * 1.0);
        }

        xData2.clear();
        yData2.clear();
        for (Integer x : mapRight.keySet()) {
            xData2.add(x * 1.0);
            yData2.add(mapRight.get(x) * 1.0);
        }
    }

    @Override
    protected void updateChart() {
        super.updateChart();
        chartPanel.updateSeries(seriesName2, xData2, yData2);
    }

    @Override
    protected Chart getChart() {
        Chart chart = super.getChart();
        chart.addSeries(seriesName2, xData2, yData2);
        return chart;
    }
}
